﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BuySoftwareOnline.Domain.Abstract;
using BuySoftwareOnline.Domain;
using BuySoftwareOnline.Web.Models;
using BuySoftwareOnline.Domain.Concrete;

namespace BuySoftwareOnline.Web.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        private IProductRepository repository;
        private ProductRepository repoo = new ProductRepository();

        public AdminController(IProductRepository repo)
        {
            repository = repo;
        }

        public ViewResult Index()
        {
            return View(repository.Products);
        }

        //
        // GET: /Admin/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Admin/Create

        public ViewResult Create()
        {
            CategoryDropDownList();
            SupplierDropDownList();
            VersionCheckBoxList(String.Empty);
            return View("Edit", new Product());
        } 

        //
        // POST: /Admin/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Admin/Edit/5
 
        public ActionResult Edit(string productID)
        {
            Product product = repository.Products.FirstOrDefault(p => p.ProductID == productID);
            if (productID != "")
            {
                SupplierDropDownList(product.SupplierID);
                CategoryDropDownList(product.CategoryID);
                VersionCheckBoxList(productID);
            }
            return View(product);
        }

        //
        // POST: /Admin/Edit/5

        public void CategoryDropDownList(object selectedCategory = null)
        {
            CategoryRepository cp = new CategoryRepository();
            ViewBag.CategoryID = new SelectList(cp.Categories.Select(p => p), "CategoryID", "CategoryName", selectedCategory);
        }

        public void SupplierDropDownList(object selectedSupplier = null)
        {
            SupplierRepository sp = new SupplierRepository();
            ViewBag.SupplierID = new SelectList(sp.Suppliers.Select(p => p), "SupplierID", "SupplierName", selectedSupplier);
        }

        public void VersionCheckBoxList(string productID)
        {
            VersionRepository vp = new VersionRepository();
            var AllVersion = vp.Versions.Select(p => p);
            ProductBuildRepository pr = new ProductBuildRepository();
            var AllProductBuild = pr.ProductBuilds.Where(p => p.ProductID == productID).Select(p => p);
            var viewModel = new List<AssignedVersionData>();
            foreach (var version in AllVersion)
            {
                viewModel.Add(new AssignedVersionData
                {
                    VersionID = version.VersionID,
                    VersionType = version.VersionType,
                    AddPrice = AllProductBuild.Select(p => p.VersionID).Contains(version.VersionID) ? AllProductBuild.Where(p => p.VersionID == version.VersionID).Select(p => p.AddPrice).SingleOrDefault().Value : 0,
                    Assigned = AllProductBuild.Select(p => p.VersionID).Contains(version.VersionID)
                });
            }
            ViewBag.Versions = viewModel;
        }
        [HttpPost]
        public ActionResult Edit(Product product, int[] selectedVersions)
        {
            try
            {
                // TODO: Add update logic here
                if (TryUpdateModel(product))
                {
                    var arrayFileType = new string[] { "image/jpeg", "image/jpg", "image/png", "image/gif" };
                    HttpPostedFileBase file = Request.Files[0];
                    if (arrayFileType.Contains(file.ContentType))
                    {
                        product.ImageType = file.ContentType;
                        product.ImageContent = new byte[file.ContentLength];
                        file.InputStream.Read(product.ImageContent, 0, file.ContentLength);
                    }
                    else
                    {
                        product.ImageContent = null;
                    }
                    HttpPostedFileBase filesc = Request.Files[1];
                    if (arrayFileType.Contains(filesc.ContentType))
                    {
                        product.ScreenShotType = filesc.ContentType;
                        product.ScreenShot = new byte[filesc.ContentLength];
                        filesc.InputStream.Read(product.ScreenShot, 0, filesc.ContentLength);
                    }
                    else
                    {
                        product.ScreenShot = null;
                    }
                    repository.SaveProduct(product);
                    if (selectedVersions.Count() != 0)
                    {
                        List<string> addprices = new List<string>();
                        foreach (var i in selectedVersions)
                        {
                            string addpriceid = "AddPrice" + i;
                            addprices.Add(Request[addpriceid]);
                        }
                        UpdateSelectedVersions(product, selectedVersions, addprices);
                    }
                    TempData["message"] = string.Format("{0} has been saved", product.ProductID);
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View(product);
            }
        }

        private void UpdateSelectedVersions(Product product,int[] selectedVersions,List<string> addprices)
        {
            ProductBuildRepository pbr = new ProductBuildRepository();
            var AllPbOfProduct = pbr.ProductBuilds.Where(p => p.ProductID == product.ProductID).Select(p => p);
            foreach (var productbuild in AllPbOfProduct)
            {
                pbr.DeleteProductBuild(productbuild);
            }
            int i=0;
            foreach (var versionid in selectedVersions)
            {
                ProductBuild pb = new ProductBuild();
                pb.VersionID = versionid;
                pb.ProductID = product.ProductID;
                int addprice;
                int.TryParse(addprices[i], out addprice);
                pb.AddPrice = addprice;
                pbr.SaveProductBuild(pb);
                i++;
            }
        }
        //
        // GET: /Admin/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Admin/Delete/5

        [HttpPost]
        public ActionResult Delete(string productID)
        {
            try
            {
                // TODO: Add delete logic here
                Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productID);
                if (prod != null)
                {
                    repository.DeleteProduct(prod);
                    TempData["message"] = string.Format("{0} was deleted", prod.ProductID);
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }
    }
}
